<template>
  <div class="orders-container">
    <el-card class="orders-card">
      <h2>Order Management</h2>
      
      <!-- Search and Filter -->
      <div class="filter-section">
        <el-input 
          v-model="searchQuery" 
          placeholder="Search orders (order number, customer name)..." 
          prefix-icon="Search"
          style="max-width: 300px; margin-right: 15px;"
        />
        <el-select v-model="filterStatus" placeholder="Filter by status" style="max-width: 200px; margin-right: 15px;">
          <el-option label="All" value=""></el-option>
          <el-option label="Pending" value="PENDING"></el-option>
          <el-option label="Processing" value="PROCESSING"></el-option>
          <el-option label="Shipped" value="SHIPPED"></el-option>
          <el-option label="Delivered" value="DELIVERED"></el-option>
          <el-option label="Cancelled" value="CANCELLED"></el-option>
        </el-select>
        <el-select v-model="filterDeliveryType" placeholder="Filter by delivery" style="max-width: 200px;">
          <el-option label="All" value=""></el-option>
          <el-option label="Shipping" value="SHIP"></el-option>
          <el-option label="Pickup" value="PICKUP"></el-option>
        </el-select>
      </div>
      
      <!-- Orders Table -->
      <el-table 
        :data="filteredOrders" 
        style="width: 100%; margin-top: 20px;" 
        v-loading="loading"
      >
        <el-table-column prop="orderNumber" label="Order Number" width="150"></el-table-column>
        <el-table-column prop="customerName" label="Customer" width="150"></el-table-column>
        <el-table-column prop="createdAt" label="Date" width="150"></el-table-column>
        <el-table-column prop="orderStatus" label="Status" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.orderStatus)" 
              disable-transitions
            >
              {{ scope.row.orderStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryType" label="Delivery" width="120">
          <template #default="scope">
            {{ scope.row.deliveryType === 'SHIP' ? 'Shipping' : 'Pickup' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="Amount" width="100">
          <template #default="scope">
            ${{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetails(scope.row)">View</el-button>
            <el-dropdown trigger="click" @command="handleStatusChange(scope.row, $event)">
              <el-button size="small" type="primary">
                Change Status <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="PENDING" v-if="isStatusChangeAllowed(scope.row.orderStatus, 'PENDING')">
                    Pending
                  </el-dropdown-item>
                  <el-dropdown-item command="PROCESSING" v-if="isStatusChangeAllowed(scope.row.orderStatus, 'PROCESSING')">
                    Processing
                  </el-dropdown-item>
                  <el-dropdown-item command="SHIPPED" v-if="isStatusChangeAllowed(scope.row.orderStatus, 'SHIPPED')">
                    Shipped
                  </el-dropdown-item>
                  <el-dropdown-item command="DELIVERED" v-if="isStatusChangeAllowed(scope.row.orderStatus, 'DELIVERED')">
                    Delivered
                  </el-dropdown-item>
                  <el-dropdown-item command="CANCELLED" v-if="isStatusChangeAllowed(scope.row.orderStatus, 'CANCELLED')" divided>
                    Cancel Order
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredOrders.length"
        />
      </div>
    </el-card>
    
    <!-- Order Details Dialog -->
    <el-dialog title="Order Details" v-model="detailsDialogVisible" width="800px">
      <div v-if="selectedOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Order Number" :span="2">
            {{ selectedOrder.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Name">
            {{ selectedOrder.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Email">
            {{ selectedOrder.customerEmail }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Phone">
            {{ selectedOrder.customerPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="getStatusType(selectedOrder.orderStatus)" disable-transitions>
              {{ selectedOrder.orderStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Delivery Type">
            {{ selectedOrder.deliveryType === 'SHIP' ? 'Shipping' : 'Pickup in Store' }}
          </el-descriptions-item>
          <el-descriptions-item label="Total Amount" :span="2">
            ${{ selectedOrder.totalAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="Created At" :span="2">
            {{ selectedOrder.createdAt }}
          </el-descriptions-item>
          <el-descriptions-item label="Delivery Address" v-if="selectedOrder.deliveryAddress">
            {{ selectedOrder.deliveryAddress }}
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">Order Items</h3>
        <el-table :data="selectedOrder.items" style="width: 100%;">
          <el-table-column prop="productName" label="Product" width="200"></el-table-column>
          <el-table-column prop="quantity" label="Qty" width="80"></el-table-column>
          <el-table-column prop="unitPrice" label="Unit Price">
            <template #default="scope">
              ${{ scope.row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="Total">
            <template #default="scope">
              ${{ scope.row.totalPrice }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="detailsDialogVisible = false">Close</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, computed } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'

export default {
  name: 'MerchantOrders',
  setup() {
    const loading = ref(false)
    const detailsDialogVisible = ref(false)
    const selectedOrder = ref(null)
    
    const searchQuery = ref('')
    const filterStatus = ref('')
    const filterDeliveryType = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // Mock data for orders
    const orders = ref([
      {
        orderNumber: 'ORD12345678',
        customerName: 'John Doe',
        customerEmail: 'john@example.com',
        customerPhone: '123-456-7890',
        orderStatus: 'DELIVERED',
        deliveryType: 'SHIP',
        totalAmount: '49.97',
        createdAt: '2023-10-15 14:30',
        deliveryAddress: '123 Main St, City, State 12345',
        items: [
          {
            productName: 'Sample Product 1',
            quantity: 1,
            unitPrice: '19.99',
            totalPrice: '19.99'
          },
          {
            productName: 'Sample Product 2',
            quantity: 1,
            unitPrice: '29.98',
            totalPrice: '29.98'
          }
        ]
      },
      {
        orderNumber: 'ORD12345679',
        customerName: 'Jane Smith',
        customerEmail: 'jane@example.com',
        customerPhone: '098-765-4321',
        orderStatus: 'SHIPPED',
        deliveryType: 'SHIP',
        totalAmount: '29.99',
        createdAt: '2023-10-16 10:15',
        deliveryAddress: '456 Oak Ave, Town, State 54321',
        items: [
          {
            productName: 'Sample Product 2',
            quantity: 1,
            unitPrice: '29.99',
            totalPrice: '29.99'
          }
        ]
      },
      {
        orderNumber: 'ORD12345680',
        customerName: 'Bob Johnson',
        customerEmail: 'bob@example.com',
        customerPhone: '555-123-4567',
        orderStatus: 'PENDING',
        deliveryType: 'PICKUP',
        totalAmount: '19.99',
        createdAt: '2023-10-16 16:45',
        items: [
          {
            productName: 'Sample Product 1',
            quantity: 1,
            unitPrice: '19.99',
            totalPrice: '19.99'
          }
        ]
      }
    ])
    
    const filteredOrders = computed(() => {
      let result = orders.value
      
      // Apply search filter
      if (searchQuery.value) {
        result = result.filter(order => 
          order.orderNumber.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          order.customerName.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      // Apply status filter
      if (filterStatus.value) {
        result = result.filter(order => order.orderStatus === filterStatus.value)
      }
      
      // Apply delivery type filter
      if (filterDeliveryType.value) {
        result = result.filter(order => order.deliveryType === filterDeliveryType.value)
      }
      
      // Apply pagination
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })
    
    const viewOrderDetails = (order) => {
      selectedOrder.value = order
      detailsDialogVisible.value = true
    }
    
    const handleStatusChange = (order, newStatus) => {
      ElMessageBox.confirm(
        `Are you sure you want to change the order status to ${newStatus}?`,
        'Confirm Status Change',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      ).then(() => {
        // In a real application, you would make an API call to update the order status
        // For now, updating the mock data
        order.orderStatus = newStatus
        ElMessage.success(`Order status updated to ${newStatus}`)
      }).catch(() => {
        // User cancelled
      })
    }
    
    const isStatusChangeAllowed = (currentStatus, newStatus) => {
      // Define valid status transitions
      const validTransitions = {
        'PENDING': ['PROCESSING', 'CANCELLED'],
        'PROCESSING': ['SHIPPED', 'CANCELLED'],
        'SHIPPED': ['DELIVERED'],
        'DELIVERED': [],
        'CANCELLED': []
      }
      
      const allowed = validTransitions[currentStatus] || []
      return allowed.includes(newStatus)
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'PENDING': return 'warning'
        case 'PROCESSING': return 'primary'
        case 'SHIPPED': return 'danger'
        case 'DELIVERED': return 'success'
        case 'CANCELLED': return 'info'
        default: return 'info'
      }
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    return {
      loading,
      detailsDialogVisible,
      selectedOrder,
      searchQuery,
      filterStatus,
      filterDeliveryType,
      currentPage,
      pageSize,
      orders,
      filteredOrders,
      viewOrderDetails,
      handleStatusChange,
      isStatusChangeAllowed,
      getStatusType,
      handleSizeChange,
      handleCurrentChange,
      ArrowDown
    }
  }
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.orders-card {
  padding: 20px;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}
</style>